package net.xju3_4.controller;


import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.Result;

import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RequestMapping("/api/file")
public class FileController {
    private static final String UPLOAD_DIR = "file";

    @RequestMapping("/download.do")
    public void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取文件名
//        String requestURI = request.getRequestURI();
//        String filename = requestURI.substring(requestURI.lastIndexOf('/') + 1);
        request.setCharacterEncoding("utf-8");
        String filename = request.getParameter("filename");
//        String uploadDir = request.getServletContext().getRealPath("") + UPLOAD_DIR + File.separator;
        // 1. 获取配置的上传目录
        String uploadDir = "D:\\Program Files\\Git\\project\\car_rental_system\\web_summer_back\\src\\main\\webapp\\files";
        System.out.println(uploadDir);
        File file = new File(uploadDir, filename);

        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setContentType(request.getServletContext().getMimeType(filename));
        response.setContentLength((int) file.length());

        try (InputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    @RequestMapping("/upload.do")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 准备上传目录
        String appPath = request.getServletContext().getRealPath("");
//        String uploadPath = appPath + UPLOAD_DIR;
        String uploadPath =  "D:\\Program Files\\Git\\project\\car_rental_system\\web_summer_back\\src\\main\\webapp\\files";

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean mkdir = uploadDir.mkdir();
            System.out.println(uploadDir.getPath() + "创建结果：" + mkdir);
        }

        try {
            // 获取上传的文件
            Part filePart = request.getPart("file");
            String fileName = filePart.getSubmittedFileName();

            // 生成唯一文件名
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID() + fileExtension;

            // 保存文件
            String filePath = uploadPath + File.separator + uniqueFileName;
            try (InputStream fileContent = filePart.getInputStream()) {
                Files.copy(fileContent, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            }

            // 返回JSON响应
            JSONUtil.printByJSON(response, Result.success(uniqueFileName));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.error(e.getMessage()));
        }
    }


//    @RequestMapping("/upload1.do")
//    public void upload1(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        // 准备上传目录
//        String uploadPath = "E:\\git\\web_summer_back\\src\\main\\webapp\\files";
//        File uploadDir = new File(uploadPath);
//        if (!uploadDir.exists()) {
//            boolean mkdir = uploadDir.mkdirs();
//            System.out.println(uploadDir.getPath() + "创建结果：" + mkdir);
//        }
//
//        try {
//            // 获取上传的文件
//            Part filePart = request.getPart("file");
//
//            // 生成唯一文件名（固定使用 .jpg 扩展名）
//            String uniqueFileName = UUID.randomUUID() + ".jpg";
//
//            // 保存文件
//            String filePath = uploadPath + File.separator + uniqueFileName;
//            try (InputStream fileContent = filePart.getInputStream()) {
//                Files.copy(fileContent, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
//            }
//
//            // 返回服务器生成的文件名
//            JSONUtil.printByJSON(response, Result.success(uniqueFileName));
//        } catch (Exception e) {
//            e.printStackTrace();
//            JSONUtil.printByJSON(response, Result.error("上传失败：" + e.getMessage()));
//        }
//    }



    @RequestMapping("/upload1.do")
    public void upload1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uploadPath = "D:\\Program Files\\Git\\project\\car_rental_system\\web_summer_back\\src\\main\\webapp\\files";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) uploadDir.mkdirs();

        try {
            Part filePart = request.getPart("file");
            String originalFileName = filePart.getSubmittedFileName();

            // 1. 提取文件扩展名
            String fileExtension = "";
            int dotIndex = originalFileName.lastIndexOf('.');
            if (dotIndex > 0) {
                fileExtension = originalFileName.substring(dotIndex);
            }

            // 2. 生成带扩展名的唯一文件名（如 uuid.jpg）
            String uniqueFileName = UUID.randomUUID() + fileExtension;
            String filePath = uploadPath + File.separator + uniqueFileName;

            // 3. 保存文件
            try (InputStream in = filePart.getInputStream()) {
                Files.copy(in, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            }

            // 4. 返回**文件名**到前端（而非完整URL）
            // 后续你可以将这个文件名存入数据库
            JSONUtil.printByJSON(response, Result.success(uniqueFileName));

        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.error("上传失败：" + e.getMessage()));
        }
    }



}
